//
//  YYForgotPwdViewController.swift
//  STMusic
//
//  Created by stoneobs on 2017/6/20.
//  Copyright © 2017年 stoneobs. All rights reserved.
//

import UIKit

class YYForgotPwdViewController: STTableViewController,STSendButtonDlegate {

    var sendButton:STSendButton?
    
    var accountTextFiled:UITextField?
    
    var codeTextFiled:UITextField?
    
    
    var pwdTextFiled:UITextField?
    
    
    var finshButton:STButton?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "忘记密码";
        self.view.backgroundColor = .white;
        self.tableView.backgroundColor = .white;
        self.initSubviews();
        NotificationCenter.default.addObserver(self, selector: #selector(didReciveNotifacationAction(notify:)), name: NSNotification.Name.UITextFieldTextDidChange, object: nil);
        // Do any additional setup after loading the view.
    }
    
    func didReciveNotifacationAction(notify:NSNotification) -> Void {
        
        if (self.accountTextFiled?.text?.characters.count)! == 11  &&
            (self.codeTextFiled?.text?.characters.count)! >= 3      &&
            (self.pwdTextFiled?.text?.characters.count)! > 5{
            
            self.finshButton?.isUserInteractionEnabled = true;
            self.finshButton?.backgroundColor = UIColor.flatMint;
        }else{
            
            self.finshButton?.isUserInteractionEnabled = false;
            self.finshButton?.backgroundColor = NO_USER_INTERFACE_COLOR;
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self);
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated);
        
        self.findHairlineImageViewUnder(self.navigationController?.navigationBar).isHidden = true;
        
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated);
        
        self.findHairlineImageViewUnder(self.navigationController?.navigationBar).isHidden = false;
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func initSubviews() -> Void {
        
        self.accountTextFiled = UITextField.init(frame: .init(x: 25, y: 10, width: SCREEN_WIDTH - 50 - 100, height: 40));
        self.accountTextFiled?.placeholder = "请输入手机号";
        self.accountTextFiled?.keyboardType = .numberPad;
        self.accountTextFiled?.textAlignment = .left;
        self.tableView.addSubview(self.accountTextFiled!);
        
        let accountLine:UIView = UIView.init(frame: CGRect.init(x: 0, y: (self.accountTextFiled?.bottom)!, width: SCREEN_WIDTH - 50, height: 1));
        accountLine.backgroundColor = LINE_COLOR;
        accountLine.centerX = SCREEN_WIDTH / 2;
        self.tableView.addSubview(accountLine);
        
        
        self.codeTextFiled = UITextField.init(frame: .init(x: 25, y: (self.accountTextFiled?.bottom)! + 20, width: SCREEN_WIDTH - 50, height: 40));
        self.codeTextFiled?.placeholder = "请输入验证码";
        self.codeTextFiled?.keyboardType = .numberPad;
        self.codeTextFiled?.centerX = SCREEN_WIDTH / 2;
        self.codeTextFiled?.textAlignment = .left;
        self.tableView.addSubview(self.codeTextFiled!);
        
        let codeLine:UIView = UIView.init(frame: CGRect.init(x: 0, y: (self.codeTextFiled?.bottom)!, width: accountLine.width, height: 1));
        codeLine.backgroundColor = LINE_COLOR;
        codeLine.centerX = SCREEN_WIDTH / 2;
        self.tableView.addSubview(codeLine);
        
        
        self.pwdTextFiled = UITextField.init(frame: .init(x: 25, y: (self.codeTextFiled?.bottom)! + 20, width: SCREEN_WIDTH - 50, height: 40));
        self.pwdTextFiled?.placeholder = "请输入新密码6 - 12 位";
        self.pwdTextFiled?.keyboardType = .asciiCapable;
        self.pwdTextFiled?.centerX = SCREEN_WIDTH / 2;
        self.pwdTextFiled?.textAlignment = .left;
        self.pwdTextFiled?.isSecureTextEntry = true;
        self.tableView.addSubview(self.pwdTextFiled!);
        let pwdLine:UIView = UIView.init(frame: CGRect.init(x: 0, y: (self.pwdTextFiled?.bottom)!, width: accountLine.width, height: 1));
        pwdLine.backgroundColor = LINE_COLOR;
        pwdLine.centerX = SCREEN_WIDTH / 2;
        self.tableView.addSubview(pwdLine);
        
        self.sendButton = STSendButton.init(frame: .init(x: 0, y: 0, width: 100, height: 16), andWithDuration: 60);
        self.sendButton?.contentHorizontalAlignment = .right;
        self.sendButton?.centerY = (self.accountTextFiled?.centerY)!;
        self.sendButton?.right = accountLine.right;
        self.sendButton?.delegate = self;
        self.sendButton?.setTitle("获取验证码", for: .normal);
        self.sendButton?.backgroundColor = .clear;
        self.sendButton?.titleLabel?.font = UIFont.systemFont(ofSize: 13);
        self.sendButton?.setTitleColor(ThirdTextColor, for: .normal);
        self.tableView.addSubview(self.sendButton!);
        
        weak var weakSelf = self;
        
        self.finshButton = STButton.init(frame: .init(x: 45, y: (self.pwdTextFiled?.bottom)! + 40, width: SCREEN_WIDTH - 90, height: 40),
                                            title: "提交",
                                            titleColor: .white,
                                            titleFont: 15,
                                            cornerRadius: 3,
                                            backgroundColor: NO_USER_INTERFACE_COLOR,
                                            backgroundImage: nil,
                                            image: nil);
        self.finshButton?.isUserInteractionEnabled = false;
        self.finshButton?.centerX = SCREEN_WIDTH / 2;
        self.finshButton?.contentHorizontalAlignment = .center;
        self.finshButton?.clicAction = { but in
            
            weakSelf?.loadForgotRequest();
        }
        self.tableView.addSubview(self.finshButton!);
        
    }
    
    //MARK:STSendButtonDlegate
    func stSendButtonShouldBecomeTheFirstResponder(whenWillClicTheSTSend sendButton: UIButton!) -> Bool {
        let myphone:NSString = NSString.init(string: (self.accountTextFiled?.text)!);
        if myphone.length == 0 {
            SVProgressHUD.showError(withStatus: "手机号不能为空");
            
            return false;
        }
        if myphone.length != 11 || !myphone.isPureNumandCharacters() {
            SVProgressHUD.showError(withStatus: "手机号格式不正确");
            
            return false;
        }
        return true;
        
    }
    func stSendButtonDidClic(_ button: UIButton!, isFirstClic: Bool, duration: Int) {
        if isFirstClic {
            
            self.loadGetCodeRequest(phone: (self.accountTextFiled?.text)!);
        }
    }
    func stSendButtonDidCountdown(_ button: UIButton!, duration: Int) {
        
        self.sendButton?.setTitle("剩余\(duration)秒", for: .normal);
    }
    func stSendButtonTimeEnded(_ button: UIButton!) {
        self.sendButton?.setTitle("重新发送", for: .normal);
        self.sendButton?.timerEnd();
    }
    
    
    // MARK:Network Request
    func loadGetCodeRequest(phone:String) -> Void {
        
        BmobSMS.requestCodeInBackground(withPhoneNumber: phone, andTemplate: "余音短信") { (num, error) in
            
            if error == nil{
                SVProgressHUD.showSuccess(withStatus: "短信验证码已发送至" + phone )
                self.sendButton?.timerBegin();
            }else{
                self.sendButton?.timerEnd();
                print("error");
            }
        }
    }
    
    func loadForgotRequest() -> Void {
        
        
        BmobUser.signOrLoginInbackground(withMobilePhoneNumber: self.accountTextFiled?.text, smsCode: self.codeTextFiled?.text, andPassword: self.pwdTextFiled?.text) { (loginUser, loginError) in
            
            if loginError == nil {
                SVProgressHUD.show(withStatus: "重置秘密成功，正在为您自动登陆");
                let rootVC = STLayoutViewController.defaultLayout();
                rootVC.leftViewController = STNavigationController.init(rootViewController: YYLeftViewController());
                rootVC.leftDisplayMode = STLayoutViewDisplayMode.background;
                rootVC.rightViewController = YYMusciPlayerController.shardPlayer;
                rootVC.rightDisplayMode = STLayoutViewDisplayMode.cover;
                //rootVC.setPanGestureEnable(false);
                self.view.window?.rootViewController = rootVC;
                SVProgressHUD.dismiss();
                SVProgressHUD.showSuccess(withStatus: "登录成功");
            }else{
            
                SVProgressHUD.showError(withStatus: loginError.debugDescription);
            }
        }
        
    }

}
